package com.sky.sentinel.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSONObject;
import com.sky.sentinel.config.SentinelConfig;
import com.sky.sentinel.service.ISentinelService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SentinelServiceImpl implements ISentinelService {

    @Value("${flowRule}")
    private String flowRule;

    @Value("${degradeRule}")
    private String degradeRule;
    /**
     * 限流降级
     * @return
     */
    @Override
    public String sayHello(String name){
        System.out.println("规则： " + flowRule);
        SentinelConfig.initFlowRule(flowRule);
        Entry entry = null;
        // 务必保证finally会被执行
        try {
            // 参数与资源名保持一致
            entry = SphU.entry("flowRule");
            // 以下可以执行业务逻辑代码
            return "hello, flowRule, "+ name;
        } catch (BlockException e1) {
            return "访问过快，限流降级, 请稍后重试!";
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }

    /**
     * 熔断降级
     * @return
     */
    //@SentinelResource(value = "circuitBreaker", fallback = "circuitBreakerFallback", blockHandler = "sayHelloExceptionHandler")
    @Override
    public String circuitBreaker(String name){
        System.out.println("规则： " + degradeRule);
        SentinelConfig.initDegradeRule(degradeRule);
        Entry entry = null;
        // 务必保证finally会被执行
        try {
            // 参数与资源名保持一致
            entry = SphU.entry("degradeRule");
            // 以下可以执行业务逻辑代码
            return "hello, degradeRule, "+ name;
        } catch (BlockException e1) {
            return "服务异常，熔断降级, 请稍后重试!";
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }
}
